package com.sunducation.wts.penbox.activity;

import static com.wetao.lib_common.EventBus.EventBusMessage.EVENT_BUS_ACTION_PEN_CONNECT_IS;
import static com.wetao.lib_common.EventBus.EventBusMessage.EVENT_BUS_ACTION_RELOGIN;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sunducation.wts.penbox.R;
import com.sunducation.wts.penbox.adapter.NoticeAdapter;
import com.sunducation.wts.penbox.contract.HomeContract;
import com.sunducation.wts.penbox.presenter.HomePresenter;
import com.wetao.lib_common.AppConfig;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsOnlineReq;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq_vo;
import com.wetao.lib_common.bean.response.AppVersionInfo;
import com.wetao.lib_common.bean.response.Loginbean;
import com.wetao.lib_common.bean.response.ReadPushListInfo;
import com.wetao.lib_common.bean.response.StudentExamListInfo;
import com.wetao.lib_common.bean.response.StudentLiveMessageInfo;
import com.wetao.lib_common.bean.response.StudyTaskCountInfo;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExamOnline;
import com.wetao.lib_common.greendao.model.PagePictureOnline;
import com.wetao.lib_common.greendao.model.StudentIdToEn;
import com.wetao.lib_common.net.cookies.CookiesManager;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.ConstantUtils;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MultiClickUtil;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.module_homework.HomeworkLineActivity;
import com.wetao.lib_common.view.dialog.CustomDialog;
import com.wetao.lib_common.view.dialog.OnCustomDialogItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * author: zhouyh
 * created on: 2020/9/11 4:47 PM
 * description: 首页
 */
@Route(path = ConstantArouter.PATH_APP_HOMEACTIVITY)
public class HomeActivity extends BaseActivity<HomeContract.View, HomePresenter> implements HomeContract.View {


    private static final String TAG = "HomeActivity";
    @Autowired(name = "fromPath")
    String mFromPath;

    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.iv_user)
    ImageView iv_user;
    @BindView(R.id.iv_read_push)
    ImageView iv_read_push;
    @BindView(R.id.lrv_home_list)
    RecyclerView rv_notice;
    @BindView(R.id.rl_home_class_interact)
    RelativeLayout rl_interaction;
    @BindView(R.id.rl_home_scientific_train)
    RelativeLayout rl_train;
    @BindView(R.id.rl_home_small_class)
    RelativeLayout rl_small_class;
    @BindView(R.id.rl_home_gather)
    RelativeLayout rl_gather;
    @BindView(R.id.rl_home_smart_pen)
    RelativeLayout rl_smart_pen;
    @BindView(R.id.tv_home_list_more)
    TextView tv_more;
    @BindView(R.id.tv_home_train_number)
    TextView tv_train_number;
    @BindView(R.id.tv_home_task_number)
    TextView tv_task_number;
    @BindView(R.id.tv_home_pen_number)
    TextView tv_pen_number;
    @BindView(R.id.rl_home_noData)
    RelativeLayout rl_empty;
    @BindView(R.id.tv_home_pen_state)
    TextView tv_home_pen_state;
    @BindView(R.id.srl_home)
    SmartRefreshLayout srl_home;
    @BindView(R.id.tv_read_push_number)
    TextView tv_read_push_number;


    private NoticeAdapter noticeAdapter;

    private List<StudentLiveMessageInfo.Data> liveList = new LinkedList<>();
    private List<StudentExamListInfo.Data.RecordsBean> examList = new LinkedList<>();
    private List<ReadPushListInfo.Data.RecordsBean> pushList = new LinkedList<>();


    private int curPage = 1;
    private int pages = 1;
    private int total = 1;
    private int PAGE = 1;
    private int PAGE_SIZE = 4;
    private String studentId;

    //轮询
    private Disposable disposable;

    @Override
    public int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    public HomePresenter createPresenter() {
        return new HomePresenter(this);
    }

    @Override
    public HomeContract.View createView() {
        return this;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void init() {
        LogUtils.e("---------主界面得到的fromPaht = " + mFromPath);
        toDbQuestion();

        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        Constants.FILE_PATH = getFilesDir().getAbsolutePath();
        LogUtils.e("存储文件的路径：" + Constants.FILE_PATH);
        String userBean = SPUtils.getInstance().getString(Constants.USER_LOGIN_INFO);
        if (userBean != null && !TextUtils.isEmpty(userBean)) {
            Loginbean loginbean = new Gson().fromJson(userBean, Loginbean.class);
            tv_user_name.setText(String.format("%s的智学雷达", loginbean.getName()));
        }
        initRecycleView();
        initRefresh();
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    @OnClick({
            R.id.rl_home_class_interact,
            R.id.rl_home_scientific_train,
            R.id.rl_home_small_class,
            R.id.rl_home_study_report,
            R.id.rl_home_gather,
            R.id.rl_home_smart_pen,
            R.id.iv_user,
            R.id.iv_read_push,
            R.id.tv_home_list_more,
            R.id.rl_home_noData,
            R.id.srl_home})
    public void click(View view) {
        int id = view.getId();
        if (id == R.id.rl_home_class_interact) {
            //课堂互动
            ARouter.getInstance().build(ConstantArouter.PATH_APP_NOTICETASKACTIVITY)
                    .withString("title", "课堂互动")
                    .withInt("type", Constants.TYPE_CLASS_INTERACTION)
                    .navigation();

        } else if (id == R.id.rl_home_scientific_train) {
            //科学训练
            ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_MAINACTIVITY)
                    .navigation();
        } else if (id == R.id.rl_home_small_class) {
            //讲题微课
            ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREMAINACTIVITY)
                    .navigation();
        } else if (id == R.id.rl_home_gather) {
            //错题斩
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_GATHER_MAINACTIVITY)
                        .navigation();
            }
        } else if (id == R.id.rl_home_smart_pen) {
            //智能笔
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY)
                        .navigation();
            }

        } else if (id == R.id.iv_user) {
            //用户中心
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_USER_USERACTIVITY)
                        .navigation();
            }
        } else if (id == R.id.tv_home_list_more) {
            //更多任务
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_APP_NOTICETASKACTIVITY)
                        .withString("title", "学习任务")
                        .withInt("type", Constants.TYPE_TASK)
                        .navigation();
            }
        }else if (id == R.id.rl_home_noData){
            getDateReq();
        }else if (id == R.id.rl_home_study_report){
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_REPORT_MAINACTIVITY)
                        .navigation();
            }
        }else if (id == R.id.iv_read_push){
            if (MultiClickUtil.isFastClick()){
                ARouter.getInstance().build(ConstantArouter.PATH_READER_READPUSHACTIVITY)
                        .navigation();
            }
        }
    }



    private void updateNotice() {

        disposable();
        Observable.interval(500, 1000 * 10, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.single())
                .subscribe(new Observer < Long > () {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.e("updateNotice start");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getStudyTaskCountReq();
                                getStudyLiveMessageReq();
                                getDateReq();
                                getReadPushListReq();
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



    public void disposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }


    private void initRefresh() {

        srl_home.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                curPage = PAGE;
                getDateReq();
            }
        });
        srl_home.setRefreshHeader(new ClassicsHeader(this));
    }


    private void finishRefresh(int type) {
        if (curPage == 1){
            resetNoMoreData();
            if (type == Constants.TYPE_TASK){
                examList.clear();
            }else if (type == Constants.TYPE_CLASS_INTERACTION){
                liveList.clear();
            }else if (type == Constants.TYPE_READ_PUSH){
                pushList.clear();
            }
        }
        finishRefresh();
    }

    //结束刷新视图
    public void finishRefresh(){
        if (srl_home != null) {
            srl_home.finishRefresh();
            srl_home.finishLoadMore();
        }
    }

    public void resetNoMoreData(){
        if(srl_home!=null){
            srl_home.resetNoMoreData();//去除没有更多数据状态
        }
    }


    private void initRecycleView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rv_notice.setLayoutManager(linearLayoutManager);
        noticeAdapter = new NoticeAdapter(this);
        noticeAdapter.setNoticeItemClickListener(new NoticeAdapter.OnNoticeItemClickListener() {
            @Override
            public void OnClassItemClickListener(StudentLiveMessageInfo.Data bean, int position) {
                if (!ComUtil.isNetworkConnected()){
                    ToastUtil.initToast("网络已断开，请先检查网络");
                    return;
                }
                if (MultiClickUtil.isFastClick()){
                    ARouter.getInstance().build(ConstantArouter.PATH_CLASSIN_MAINROOMACTIVITY)
                            .withString("lessonName", bean.getLessonName())
                            .withString("roomName", bean.getRoomName())
                            .withString("studentId", String.valueOf(bean.getStudentId()))
                            .navigation();
                }

            }

            @Override
            public void OnExamItemClickListener(StudentExamListInfo.Data.RecordsBean item,int position) {
                if (!MultiClickUtil.isFastClick()){
                    return;
                }
                if (item == null)return;
                if( 3 == item.getState()) {//考试已结束,学生未提交
                    DialogXUtil.customDialogShow("当前作答已超时,\r\n已作答数据将自动提交。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    exceptionSubmitCount = 0;
                    setQuestionAnswer(item);
                    return;
                }

                if(0== item.getState()) {//考试未开始
                    DialogXUtil.customDialogShow( "当前未到作答时间,\r\n请在作答时间内作答。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    return;
                }

                if (!ComUtil.isNetworkConnected()){
                    ToastUtil.initToast("网络已断开，请先检查网络");
                    return;
                }
                ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_LINEACTIVITY)
                        .withString("examName",item.getExamName())
                        .withInt("examId",item.getExamId())
                        .withInt("publishId",item.getExamPublishId())
                        .withInt("studentExamId",item.getStudentExamId())
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .navigation();
            }

            @Override
            public void OnPushItemClickListener(ReadPushListInfo.Data.RecordsBean bean) {
                if (MultiClickUtil.isFastClick()){
                    gotoPushDetailActivity(bean);
                }
            }

        });
        rv_notice.setAdapter(noticeAdapter);
    }


    /**
     * 请求任务数量
     */
    private void getStudyTaskCountReq() {
        getPresenter().getHomePageCount(false, false);
    }


    private void getDateReq(){
        getStudentExamListReq();
    }

    public void getReadPushListReq(){
        getPresenter().getReadPushList(ComUtil.getHashmapByStr(
                new String[]{"pageNo","pageSize"},
                new String[]{ String.valueOf(curPage), String.valueOf(PAGE_SIZE)})
                , false, false);
    }

    /**
     * 请求课堂互动列表数据
     */
    private void getStudyLiveMessageReq() {
        getPresenter().getStudentLiveMessageList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"pageNo", "pageSize"},
                new Object[]{curPage,PAGE_SIZE}),false, false);
    }

    private void getStudentExamListReq() {
        getPresenter().getHomeStudentExamList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"itemSubject","state","pageNo", "pageSize"},
                new Object[]{null,0,curPage,PAGE_SIZE}), false, false);
    }


    private void getVersionReq() {
        getPresenter().getClientVersionInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"version"},
                new Object[]{ConstantUtils.getAppVersionName()}), false, false);
    }


    /**
     * 智能笔未提交数量
     * @return
     */
    private int noSubmitNum() {
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        return SPUtils.getInstance().getInt(Constants.USER_PEN_OFFLINE_NOSUBMITNUM + "_" + studentId, 0);
    }


    @Override
    protected void onPause() {
        super.onPause();
        disposable();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateNotice();
        getVersionReq();
        runOnUiThread(() -> {
            if (noSubmitNum() == 0){
                tv_pen_number.setVisibility(View.GONE);
            }else {
                tv_pen_number.setVisibility(View.VISIBLE);
                tv_pen_number.setText(String.format("%s",noSubmitNum()));
            }
        });
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_TSDSERVICE_RESETDATA, this.getClass().getName()));
    }

    @Override
    protected void onUserLeaveHint() {
        LogUtils.i("onUserLeaveHint");
        super.onUserLeaveHint();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e("onDestroy start");
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }

    }


    @Override
    public void getStudyTaskCountResult(StudyTaskCountInfo resp) {
        showTaskNumber(resp.getData() == null ? null : resp.getData());
    }

    @Override
    public void getStudyTaskCountFail() {

    }

    @Override
    public void getStudentLiveMessageListResult(StudentLiveMessageInfo resp) {
        finishRefresh(Constants.TYPE_CLASS_INTERACTION);
        if (resp.getData() != null && resp.getData().size() > 0) {
            liveList.addAll(resp.getData());
        }
        //刷新任务列表，最多显示4条数据
        hasExamVisible();
        noticeAdapter.setClassData(liveList);

        showEmpty();
    }

    @Override
    public void getStudentLiveMessageListFail() {

    }

    @Override
    public void getHomeStudentExamListResult(StudentExamListInfo resp) {
        finishRefresh(Constants.TYPE_TASK);
        if (resp.getData() != null && resp.getData().getSize() > 0) {
            for (int i = 0; i < resp.getData().getRecords().size(); i++) {
                StudentExamListInfo.Data.RecordsBean item = resp.getData().getRecords().get(i);
                AssistantExamOnline examOnline = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(item.getExamPublishId(), item.getExamId(), studentId);
                if(null != examOnline) {
                    item.setAnswerAmount(examOnline.getDealNum());
                }
            }
            examList.addAll(resp.getData().getRecords());
        }

        if (!hasExamVisible()){
           noticeAdapter.setExamData(examList);
        }
        showEmpty();
    }


    public boolean hasExamVisible(){
        boolean more = false;
        int liveSize = liveList.size();
        int examSize = examList.size();
        if (liveSize >= PAGE_SIZE){
            examList.clear();
            pushList.clear();
        }else{
            //如果作业数量大于剩余显示数量
            int left = PAGE_SIZE - liveSize;
            List<StudentExamListInfo.Data.RecordsBean> temp = new LinkedList<>();
            if (examSize >= left){
                temp.addAll(examList.subList(0,left));
            }else {
                temp.addAll(examList);
            }
            noticeAdapter.setExamData(temp);
            more = true;
        }
        return more;
    }

    public boolean hasPushVisible(){
        boolean more = false;
        int sum = liveList.size() + examList.size();
        int pushSize = pushList.size();
        if (sum >= PAGE_SIZE){
            pushList.clear();
        }else{
            //如果作业数量大于剩余显示数量
            int left = PAGE_SIZE - sum;
            List<ReadPushListInfo.Data.RecordsBean> temp = new LinkedList<>();
            if (pushSize >= left){
                temp.addAll(pushList.subList(0,left));
            }else {
                temp.addAll(pushList);
            }
            noticeAdapter.setPushData(temp);
            more = true;
        }
        return more;
    }

    @Override
    public void getClientVersionResult(BaseResponse<AppVersionInfo> data) {
        if (null == data) return;
        LogUtils.i("getClientVersionResult data " + data.toString());
        AppVersionInfo appVersionInfo = data.getData();
        if (null != appVersionInfo) {
            if (!TextUtils.isEmpty(appVersionInfo.getDownloadUrl())) {
                showUpgradeDialog(appVersionInfo.getVersion(), ComUtil.getApkSize(appVersionInfo.getApkSize()),
                        appVersionInfo.getDescription(), appVersionInfo);
            }
        }
    }

    @Override
    public void getClientVersionError() {

    }

    private void showEmpty() {
        if (noticeAdapter.getItemCount() > 0) {
            rl_empty.setVisibility(View.GONE);
            srl_home.setVisibility(View.VISIBLE);
        } else {
            rl_empty.setVisibility(View.VISIBLE);
            srl_home.setVisibility(View.GONE);
        }
    }

    @Override
    public void getHomeStudentExamListFail() {
        finishRefresh();
    }


    @Override
    public void getCommitAnswerResult(BaseResponse response) {
        ToastUtil.initToast("强制提交成功！");

        getDateReq();

        getStudyTaskCountReq();
    }

    @Override
    public void getCommitAnswerFailed() {
        ToastUtil.initToast("提交失败！");
    }

    @Override
    public void getReadPushListResult(ReadPushListInfo resp) {
        finishRefresh(Constants.TYPE_READ_PUSH);
        pushList.clear();
        if (resp.getData() != null && resp.getData().getSize() > 0) {
            List<ReadPushListInfo.Data.RecordsBean> tempList = new ArrayList<>();
            tempList.addAll(resp.getData().getRecords());
            for (ReadPushListInfo.Data.RecordsBean bean : tempList){
                if (bean.getReadStatus() == 3){
                    pushList.add(bean);
                }
            }
        }
        if (!hasPushVisible()){
            noticeAdapter.setPushData(pushList);
        }
        showEmpty();
    }

    @Override
    public void getReadPushListFailed() {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        //LogUtils.i("m1: bus" + messageEvent.toString());
        if (messageEvent.getAction() == EVENT_BUS_ACTION_PEN_CONNECT_IS){
            tv_home_pen_state.setText(String.format("(%s)",messageEvent.getMsg()));
        }else if (messageEvent.getAction() == EVENT_BUS_ACTION_RELOGIN){
            LogUtils.e("releaseTimer");
//            releaseTimer();
            disposable();
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)// sticky =true,可以接收粘性事件。
    public void busStickyMessage(EventBusMessage messageEvent) {
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS){
            if(TextUtils.isEmpty(msg)) return;
            String[] str = messageEvent.getMsg().split("###");
            // notifyAnswerProgress(Integer.parseInt(str[0]), Integer.parseInt(str[1]));
            int examId = Integer.parseInt(str[0]);
            int publishId = Integer.parseInt(str[1]);
            int progress = Integer.parseInt(str[2]);

            if(null != examList) {
                int pos = -1;
                for (int i = 0; i < examList.size(); i++) {
                    if(publishId == examList.get(i).getExamPublishId().intValue()
                            && examId == examList.get(i).getExamId().intValue() ) {
                        pos = i;
                        break;
                    }
                }
                if(pos > -1) {
                    examList.get(pos).setAnswerAmount(progress);
                    noticeAdapter.notifyItemChanged(pos);
                }
            }
        }
    }


    /**
     * 显示任务数量
     * @param data
     */
    private void showTaskNumber(StudyTaskCountInfo.Data data) {
        if (data.getStudyTaskCount() != null && data.getStudyTaskCount() > 0) {
            tv_task_number.setVisibility(View.VISIBLE);
            if (data.getStudyTaskCount() > 99){
                tv_task_number.setText(String.format("%s","99+"));
                tv_task_number.setBackgroundResource(R.drawable.round_number_more);
            }else {
                tv_task_number.setText(String.format("%s",data.getStudyTaskCount()));
                tv_task_number.setBackgroundResource(R.drawable.round_number);
            }
        } else {
            tv_task_number.setVisibility(View.GONE);
        }

        if (data.getExamTaskCount() != null && data.getExamTaskCount() > 0) {
            tv_train_number.setVisibility(View.VISIBLE);
            if (data.getExamTaskCount() > 99){
                tv_train_number.setText(String.format("%s","99+"));
                tv_train_number.setBackgroundResource(R.drawable.round_number_more);
            }else {
                tv_train_number.setText(String.format("%s",data.getExamTaskCount()));
                tv_train_number.setBackgroundResource(R.drawable.round_number);
            }
        } else {
            tv_train_number.setVisibility(View.GONE);
        }

        if (data.getReadPushCount() != null && data.getReadPushCount() > 0) {
            tv_read_push_number.setVisibility(View.VISIBLE);
            if (data.getReadPushCount() > 99){
                tv_read_push_number.setText(String.format("%s","99+"));
                tv_read_push_number.setBackgroundResource(R.drawable.round_number_more);
            }else {
                tv_read_push_number.setText(String.format("%s",data.getReadPushCount()));
                tv_read_push_number.setBackgroundResource(R.drawable.round_number);
            }
        } else {
            tv_read_push_number.setVisibility(View.GONE);
        }
    }
    

    private CustomDialog mCustomDialogUpgrade;

    private void showUpgradeDialog(String newVersion, String versionSize, String versionDes, AppVersionInfo versionInfo) {
        // if(null == mCustomDialogUpgrade)
        {
            mCustomDialogUpgrade = new CustomDialog(this,
                    R.layout.user_dialog_version_upgrade,
                    new int[]{R.id.ib_delete, R.id.bt_ok, R.id.tv_version_desc},
                    0,
                    false,
                    false,
                    Gravity.CENTER);
            mCustomDialogUpgrade.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.bt_ok) {
                        ARouter.getInstance().build(ConstantArouter.PATH_APP_UPDATEACTIVITY)
                                .withString("versionInfo", JsonUtils.toJson(versionInfo))
                                .navigation();
                    }
                }
            });
        }

        mCustomDialogUpgrade.setCancelable(false);

        mCustomDialogUpgrade.show();

        final List<View> viewList = mCustomDialogUpgrade.getViews();
        if (null != viewList) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("版本: %s", newVersion)).append("\n");
            sb.append(String.format("大小: %s", versionSize)).append("\n");
            sb.append("更新内容:").append("\n");
            sb.append(versionDes);
            ((AppCompatTextView) viewList.get(2)).setText(sb.toString());

            viewList.get(0).setVisibility(View.INVISIBLE);
        }
    }


    private int exceptionSubmitCount = 0;
    private void setQuestionAnswer(StudentExamListInfo.Data.RecordsBean bean) {
        if(!ComUtil.isNetworkConnected()){
            ToastUtil.initToast(getString(com.wetao.lib_common.R.string.network_disconnect));
            return;
        }

        List<CommitAssistantQuestionsReq_vo> answerList = new ArrayList<>();
        HashMap<String, String> answerMap = null;
        HashMap<Integer,Integer> timerMap = null;
        AssistantExamOnline assistantExam = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(bean.getExamPublishId(), bean.getExamId(), SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        if(null != assistantExam && !TextUtils.isEmpty(assistantExam.getTempAnswer())
                && (answerMap = JsonUtils.fromJson(assistantExam.getTempAnswer(),
                new TypeToken<HashMap<String, String>>() {}.getType())) != null) {
            LogUtils.i("answerMap = " + GsonUtil.GsonString(answerMap));

            if (assistantExam.getTempTimer()!=null){
                timerMap = JsonUtils.fromJson(assistantExam.getTempTimer(),
                        new TypeToken<HashMap<Integer, Integer>>() {}.getType());
            }

            List<String> emptyNetList = null;
            for (Map.Entry<String, String> entry : answerMap.entrySet()){
                String questionInfo = entry.getKey();
                String[] quest = questionInfo.split("###");
                if(QuestionTypeUtil.isSubjectQuestion(Integer.parseInt(quest[1]))
                        && !TextUtils.isEmpty(entry.getValue())){
                    String[] tmp = entry.getValue().split("###");
                    for (int k = 0; k < tmp.length; k++) {
                        PagePictureOnline pagePicture = DBUtils.getInstance(this)
                                .getPagePictureOnlineByPictureLocal(tmp[k]);
                        if(null != pagePicture) {
                            if(TextUtils.isEmpty(pagePicture.getPictureUrl())
                                    && new File(pagePicture.getLocalPath()).exists()){
                                if(null == emptyNetList) {
                                    emptyNetList = new ArrayList<>();
                                }
                                emptyNetList.add(pagePicture.getLocalPath());
                            }
                        }
                    }
                }
            }

            //当前有作答图盘不存在上传图片地址,递归上传图片,上传完后再提交
            if(null != emptyNetList && emptyNetList.size() > 0 && exceptionSubmitCount < 3){
                exceptionSubmitCount++;
                // EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPLOAD_ERROR_SUBMIT, JsonUtils.toJson(emptyNetList)));
                uploadSubmit(emptyNetList, bean);
                return;
            }
            exceptionSubmitCount = 0;

            int key = 0;
            for (Map.Entry<String, String> entry : answerMap.entrySet()) {
                String item = entry.getValue();
                if (!TextUtils.isEmpty(item)) {
                    String question = entry.getKey();
                    if(TextUtils.isEmpty(question)) continue;

                    String[] quesInfo = question.split("###");
                    int questionId = Integer.parseInt(quesInfo[0]);
                    int questionType = Integer.parseInt(quesInfo[1]);

                    if(item.contains(".png") || item.contains(".jpg")) {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setAnswerType(2);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        LogUtils.d("item = " + item);
                        String picUrls = getPicUrls(item, emptyNetList);
                        LogUtils.d("picUrls = " + picUrls);
                        /*if (TextUtils.isEmpty(picUrls))
                            return;*/
                        answer.setAnswerContent(picUrls);
                        answerList.add(answer);
                    } else {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setAnswerType(1);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        answer.setAnswerContent(item);
                        answerList.add(answer);
                    }
                    key++;
                }
            }
        }

        CommitAssistantQuestionsOnlineReq req = new CommitAssistantQuestionsOnlineReq();
        req.setPublishId(bean.getExamPublishId());
        req.setStudentId(SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        req.setStudentExamId(bean.getStudentExamId());

        req.setQuestionList(answerList);
        req.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        req.setBeginTime(null != assistantExam ? assistantExam.getBeginTime() : req.getFinishTime());

        getPresenter().getCommitAnswer(GsonUtil.GsonString(req), false, "正在提交已作答考试...", false);
    }

    private String getPicUrls(String str, List<String> exceptList) {
        String[] tmp = str.split("###");
        StringBuilder sb = new StringBuilder();

        for (int k = 0; k < tmp.length; k++) {
            if(null != exceptList && exceptList.contains(tmp[k])) continue;

            PagePictureOnline pagePicture = DBUtils.getInstance(this)
                    .getPagePictureOnlineByPictureLocal(tmp[k]);
            if (null != pagePicture && !TextUtils.isEmpty(pagePicture.getPictureUrl())) {
                sb.append(pagePicture.getPictureUrl());
                if (k != tmp.length - 1) {
                    sb.append(",");
                }
            }
        }

        return sb.toString();
    }

    private void uploadSubmit(List<String> exceptionPath, StudentExamListInfo.Data.RecordsBean bean){
        //DialogXUtil.waitDialogShow("正在同步作答...");
        upload(exceptionPath, 0, new HomeworkLineActivity.OnListenProcess() {
            @Override
            public void onListenStart() {

            }

            @Override
            public void onListenEnd(String uploadFile, String localFile, List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(HomeActivity.this)
                        .getPagePictureOnlineByPictureLocal(localFile);
                if (null != pagePictureOnline) {
                    LogUtils.i(localFile + " : " + uploadFile);
                    pagePictureOnline.setPictureUrl(uploadFile);
                    DBUtils.getInstance(HomeActivity.this).updatePagePictureOnline(pagePictureOnline);
                }

                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenError(List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenAllEnd() {
                //DialogXUtil.waitDialogDismiss();
                setQuestionAnswer(bean);
            }
        });
    }

    private synchronized void upload(final List<String> list, final int index, final HomeworkLineActivity.OnListenProcess onListenProcess) {
        LogUtils.i("upload index = " + index + " size = " + list.size());
        if(index >= list.size()){
            if(null != onListenProcess) {
                onListenProcess.onListenAllEnd();
            }
            return;
        }

        LogUtils.i("upload 002");
        final String temp = list.get(index);
        if(TextUtils.isEmpty(temp) || !new File(temp).exists()){
            if(null != onListenProcess) {
                onListenProcess.onListenError(list, index+1, onListenProcess);
            }
            return;
        }

        if(null != onListenProcess) {
            onListenProcess.onListenStart();
        }
        //这里保存的是原始图路径，需要转换成切图路径上传
        String clipPath = temp.substring(0,temp.lastIndexOf(".")) + "clip" + ".png";
        StringBuilder uploadFile = new StringBuilder();
        uploadFile.append(FileUtils.getFileNameNoExtension(clipPath));
        uploadFile.append("_");
        uploadFile.append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()));
        uploadFile.append(".png");
        LogUtils.i(temp + " : " + uploadFile.toString());
        UploadOss.getInstance().upload2OSS(uploadFile.toString(), clipPath, new UploadOss.OnUploadListener() {
            @Override
            public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
                if(null != onListenProcess) {
                    onListenProcess.onListenEnd(uploadFile, localFile, list, index+1, onListenProcess);
                }
                return null;
            }

            @Override
            public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
                if(null != onListenProcess) {
                    onListenProcess.onListenError(list, index+1, onListenProcess);
                }
                return null;
            }
        }, null);
    }


    /**
     * 跳转阅读页面
     * @param bean
     */
    private void gotoPushDetailActivity(ReadPushListInfo.Data.RecordsBean bean){
        if (bean == null || bean.getFileUrl() == null){
            ToastUtil.initToast("没有找到文件路径");
            return;
        }
        ARouter.getInstance().build(ConstantArouter.PATH_READER_READPUSHDETAILACTIVITY)
                .withString("fileUrl",bean.getFileUrl())
                .withString("title",bean.getReadPushTitle())
                .withString("readPushItem",JsonUtils.toJson(bean))
                .withInt("state",bean.getReadStatus())
                .withString("records", JsonUtils.toJson(pushList))
                .navigation();
    }

    private void toDbQuestion() {
        studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        boolean is_VERSION_1_3_5_TO_7 = SPUtils.getInstance().getBoolean(Constants.VERSION_1_3_5_TO_7, false);
        boolean is_VERSION_1_3_7_TO_8 = SPUtils.getInstance().getBoolean(Constants.VERSION_1_3_7_TO_8, false);
        if(!is_VERSION_1_3_5_TO_7 || !is_VERSION_1_3_7_TO_8) {
            SPUtils.getInstance().put(Constants.VERSION_1_3_5_TO_7, true);
            SPUtils.getInstance().put(Constants.VERSION_1_3_7_TO_8, true);
            DBUtils.getInstance(this).deleteAllTable(studentId);
        } else {

            //删除表PenOffLineGridInfo中所有picid=0的旧数据（草稿纸）
            DBUtils.getInstance(this).deletePenOffLineGridInfoByPicId0();
        }


        StudentIdToEn studentIdToEn = DBUtils.getInstance(this).getStudentIdToEnByStudentId(studentId);
        if(studentIdToEn == null) {
            //第一次进入这个账号
            DBUtils.getInstance(this).insertStudentIdToEn(new StudentIdToEn(null, studentId, AppConfig.BASE_URL));
        }else if(AppConfig.BASE_URL.equals(studentIdToEn.getHost())) {
            //这个账号没有切换过环境
        } else {
            if (ConstantArouter.PATH_COMMON_LOGINACTIVITY.equals(mFromPath)) {
                //从登陆界面跳转过来的, 切这个账号切换过环境，清空这个账号的数据。
                studentIdToEn.setHost(AppConfig.BASE_URL);
                DBUtils.getInstance(this).updateStudentIdToEn(studentIdToEn);
                DBUtils.getInstance(this).deleteAllTable(studentId);
            } else {
                //这个账号切换过环境，且不是从登陆界面过来的，需要退出登录。
                //从其他界面跳转过来的, 退出登录
                DBUtils.getInstance(this).close();
                DBUtils.getInstance(this).clear();


                //清除所有Cookies缓存内容
                CookiesManager.clearAllCookies();
                SPUtils.getInstance().put(Constants.HEAD_XTOKEN, "");
                SPUtils.getInstance().put(Constants.USER_ID_KEY, "");

                ARouter.getInstance().build(ConstantArouter.PATH_COMMON_LOGINACTIVITY)
                        .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                                |Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation();
            }
        }
    }


}
